package com.vm.db;

import java.util.ArrayList;
import java.util.List;

import com.vm.model.Collection;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;

public class CollectionDao {
	private static final String TAG = "CollectionDao";

	public CollectionDao(Context context) {
		if (DBOpenHelper.db == null) {
			new DBOpenHelper(context);
		}
	}

	public synchronized void insert(Collection collection) {
		Log.d(TAG, "insert");
		try {
			DBOpenHelper.db
					.execSQL(
							"INSERT INTO collection(softId,name,imageUrl,size,star,apkUrl) VALUES(?, ?,?,?,?,?)",
							new Object[] { collection.getSoftId(),
									collection.getName(),
									collection.getImageurl(),
									collection.getSize(), collection.getStar(),
									collection.getApkUrl() });
		} catch (Exception e) {
			Log.d(TAG, "insert---" + e.getMessage());
		}
	}

	public synchronized void delete(String softid) {
		Log.d(TAG, "delete");
		try {
			DBOpenHelper.db.execSQL("DELETE FROM collection where softId=?",
					new Object[] { softid });
		} catch (SQLException e) {
			Log.d(TAG, "delete---" + e.getMessage());
		}
	}

	public synchronized List<Collection> selectall() {
		Log.d(TAG, "selectall");
		List<Collection> list = new ArrayList<Collection>();
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery("SELECT * FROM collection", null);
			while (c.moveToNext()) {
				Collection collection = new Collection();
				collection = new Collection();
				collection.setSoftId(c.getString(0));
				collection.setName(c.getString(1));
				collection.setImageurl(c.getString(2));
				collection.setSize(c.getFloat(3));
				collection.setStar(c.getInt(4));
//				collection.setApkUrl(c.getString(5));
				list.add(collection);
			}
		} catch (SQLException e) {
			Log.d(TAG, "selectall---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return list;
	}

	public boolean ifExits(String softid) {
		Log.d(TAG, "ifExists");
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery(
					"select * from collection where softId=?",
					new String[] { softid });
			if (c.moveToNext()) {
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(TAG, "ifExists---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return false;
	}
}